<template>
  <div>
    <vab-card>
      <template #header>
        <span class="leve_title">订单列表</span>
      </template>
      <template #default>
        <el-form
          :ref="(el: any) => (searchFormRef = el)"
          :model="searchForm"
          label-width="100px"
          class="form_search"
        >
          <el-row :gutter="24">
            <el-col
              v-for="(item, i) in orderTrackSearch"
              v-bind="colLayout"
              :key="i"
            >
              <!-- 默认项 -->
              <el-form-item
                v-if="item.type == 'select'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabSelectForm
                  :multiple="item.multiple"
                  v-model.trim="searchForm[item.prop]"
                  :options="selectOptions(item.prop)"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- input -->
              <el-form-item
                v-if="item.type == 'input'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabInputForm
                  v-model.trim="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- time -->
              <el-form-item
                v-if="item.type == 'time'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabTimeForm
                  v-model="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- time -->
              <el-form-item
                v-if="item.type == 'lazySelect'"
                :label="item.label"
                :prop="item.prop"
              >
                <LazySelect
                  type="product_code"
                  class="width_100"
                  :multiple="item.multiple"
                  v-model="searchForm[item.prop]"
                />
              </el-form-item>
              <!-- time -->
              <el-form-item
                v-if="item.type == 'range'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabRangeForm
                  :precision="2"
                  :ref="(el) => (vabRangeFormRef = el)"
                  v-model="searchForm[item.prop]"
                />
              </el-form-item>
            </el-col>
            <!-- 按钮 -->
            <el-col v-bind="colBtn">
              <div class="flex_just_end" style="padding-top: 4px">
                <el-button size="small" type="primary" @click="handleSearch()">
                  查询
                </el-button>
                <el-button size="small" @click="resetForm(searchFormRef)">
                  重置
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </vab-card>
    <vab-card shadow="always">
      <template #header>
        <div class="flex_sb">
          <span class="leve2_title">订单明细</span>
          <div class="flex_just_end">
            <VabAuthButton
              update
              title="去付款"
              @click="handleClick('toRecharge')"
            />
            <VabAuthButton
              update
              title="确认收货"
              @click="handleClick('confirm')"
            />
            <!-- <el-button
              size="small"
              class="button_update"
              @click="handleClick('copy')"
            >
              复制
            </el-button>
            <el-button
              size="small"
              class="button_update"
              @click="handleClick('create')"
            >
              新建
            </el-button>
            <el-button size="small" @click="handleClick('close')">
              取消
            </el-button> -->
          </div>
        </div>
      </template>
      <el-table
        border
        height="430"
        style="width: 100%"
        ref="multipleTableRef"
        :data="data.dataSource"
        v-loading="data.loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" width="40" />
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            <span
              class="ellipsis"
              v-text="(data.pageNum - 1) * data.pageSize + (scope.$index + 1)"
            ></span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, i) in data.cloums"
          :key="i"
          :min-width="item.width || 180"
          :prop="item.prop"
          :label="item.label"
          :align="
            item.type == 'money' || item.type == 'number' ? 'right' : 'center'
          "
        >
          <template #header>
            <div class="flex">
              <span class="text_center">
                {{ item.label }}
              </span>
              <div class="cursor_pointer" v-if="item.shortName">
                <!-- triangle_up_active -->
                <span
                  class="triangle_up"
                  :class="{
                    triangle_up_active: `${item.prop}_asc` == shortActive,
                  }"
                  @click="handleShort(item.prop, 'asc')"
                ></span>
                <span
                  class="triangle_down"
                  :class="{
                    triangle_down_active: `${item.prop}_desc` == shortActive,
                  }"
                  @click="handleShort(item.prop, 'desc')"
                ></span>
              </div>
            </div>
          </template>
          <template #default="scope">
            <!-- 自定义 -->
            <div v-if="item.type == 'custom'">
              <span v-if="item.prop == 'order_status_str'" class="tagStatus">
                <el-tag
                  :type="statusColor(scope.row.order_status_str)"
                  style="cursor: pointer"
                  @click="handleClick('flow', scope.row)"
                >
                  {{ scope.row.order_status_str || '--' }}
                </el-tag>
              </span>
              <span
                class="text_center flex_center"
                v-if="item.prop == 'order_no'"
              >
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="信用额度超额"
                  placement="top"
                  v-if="scope.row.credit_status == 0"
                >
                  <vab-icon style="color: #ff9000" icon="notification-fill" />
                </el-tooltip>

                <span
                  class="ellipsis link"
                  @click="
                    router.push(
                      '/procure/orderTrackDateil?order_no=' + scope.row.order_no
                    )
                  "
                >
                  {{ scope.row.order_no || '--' }}
                </span>
              </span>
              <span class="text_center" v-if="item.prop == 'after_sale'">
                <el-tag>
                  {{ scope.row.after_sale == '0' ? '未出库' : '--' }}
                </el-tag>
              </span>
            </div>
            <!-- 正常 -->
            <div v-else class="ellipsis">
              {{ _FieldFormat(scope.row[item.prop], item.type) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100" fixed="right">
          <template #default="{ row }">
            <VabAuthButton
              type="primary"
              :title="Number(row.order_status) == 0 ? '去处理' : '订单确认'"
              v-if="
                Number(row.order_status) == 0 || Number(row.order_status) == 120
              "
              @click="handleClick('toHandle', row)"
            />
            <VabButton
              type="primary"
              title="查看详情"
              v-if="isShowDateil(row.order_status)"
              @click="
                router.push(
                  '/procure/orderTrackDateil?order_no=' + row.order_no
                )
              "
            />
          </template>
        </el-table-column>
      </el-table>
      <div class="flex_just_end">
        <el-pagination
          background
          small="small"
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total, prev, pager, next,sizes, jumper"
          :page-sizes="[20, 50, 100, 200]"
          :pager-count="10"
          :total="data.count"
          @current-change="handlePageNum"
          @size-change="handlePageSize"
        />
      </div>
      <VabAuthButton update title="下载" @click="_onExportBasicExcel" />
    </vab-card>
    <!-- 流程图 -->
    <FlowDialog :ref="(el: any) => (flowDialogRef = el)" />
    <!-- 确认收货 -->
    <ConfirmReceiptDialog
      ref="confirmReceiptDialogRef"
      @refresh="refreshData()"
    />
    <!-- 充值 -->
    <RechargeNewDialog ref="rechargeDialogRef" @refresh="refreshData()" />
  </div>
</template>
<!-- 库存查询 -->
<script lang="ts" setup>
  defineOptions({
    name: 'ProcureCheck',
  })
  /**
   * @import
   */
  import {
    DateFormat,
    FieldFormat,
    MoneyFormat,
    NumberFormat,
    StrShift,
  } from '~/src/utils/utils'
  import { ElMessageBox, FormInstance } from 'element-plus'
  import {
    customerOrderList,
    customerOrderUpdateStatus,
    getSearchBase,
  } from '~/src/api/dms/customerOrder'

  import { getCustomerCategoryList } from '~/src/api/dms/home/homeCustomer'
  import {
    OtherOutSearchSelect,
    orderTrackCloums,
    orderTrackSearch,
  } from '../components/tools'
  import { getBaseList } from '~/src/api/dms/public'
  import FlowDialog from './components/FlowDialog.vue'
  import LazySelect from '/@/components/lazySelect/index.vue'
  import RechargeNewDialog from './components/RechargeNewDialog.vue'
  import ConfirmReceiptDialog from './components/ConfirmReceiptDialog.vue'
  import { onExportBasicExcel } from '~/src/utils/excelJs'
  /**
   * @var
   */
  const colLayout = {
    xs: 24,
    sm: 12,
    md: 12,
    lg: 8,
    xl: 6,
  }
  const colBtn = {
    xs: 24,
    sm: 24,
    md: 24,
    lg: 24,
    xl: 24,
  }
  const proxy: any = getCurrentInstance()?.proxy
  const router = useRouter()

  const searchFormRef = ref<any>(null)
  const multipleTableRef = ref()
  const searchForm = reactive<any>({})
  const vabRangeFormRef = ref<any>()
  const flowDialogRef = ref()
  const confirmReceiptDialogRef = ref()
  const rechargeDialogRef = ref()

  // 排序方式
  const shortActive = ref<any>('')
  // 排序信息
  const sortInfo = reactive<any>({
    sort: '',
    sort_field: '',
  })

  const data = reactive<any>({
    dataSource: [],
    cloums: [],
    pageNum: 1,
    pageSize: 20,
    count: 0,
  })
  data.dataSource = []
  data.cloums = orderTrackCloums

  const screenOptions = reactive<any>({
    categoryList: [],
  })
  let isCheck = ref(false)
  // 订单占有弹窗
  const currentRow = ref<any>([]) //选中块

  /**
   * @method
   */
  // 刷新数据
  const refreshData = () => {
    multipleTableRef.value!.clearSelection()
    currentRow.value = []
    data.pageNum = 1
    _GetProductList()
  }

  const handleSearch = async (value = '') => {
    isCheck.value = true
    await _GetProductList()
    proxy.$Message('查询成功', 'success')
  }
  // 重置
  const resetForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    isCheck.value = false
    currentRow.value = []
    await vabRangeFormRef.value.reset()
    await formEl.resetFields()
    data.pageNum = 1
    await _GetProductList()
    proxy.$Message('重置成功', 'success')
  }
  // 回车
  const onkeydown = (value: any) => {
    isCheck.value = true
    _GetProductList()
  }

  // 单选
  const handleSelectionChange = (row: any) => {
    currentRow.value = row
  }
  // 页码
  const handlePageNum = (value: any) => {
    data.pageNum = value
    _GetProductList()
  }
  // 页数
  const handlePageSize = (value: any) => {
    data.pageSize = value
    _GetProductList()
  }

  // 排序
  const handleShort = (prop: string, shortType: string) => {
    shortActive.value = `${prop}_${shortType}`

    sortInfo.sort = shortType
    sortInfo.sort_field = prop

    _GetProductList()
  }

  // 点击事件
  const handleClick = (value: any, row: any = {}) => {
    // 打开流程图
    if (value == 'flow') {
      flowDialogRef.value.open(row.nodes)
      return
    }
    // 去处理
    if (value == 'toHandle') {
      router.push({
        path:
          Number(row.order_status) == 0
            ? '/procure/create'
            : '/procure/orderTrackDateil',
        query: {
          order_no: row.order_no,
          from_type: value,
        },
      })
      return
    }

    // 详情
    if (value == 'toDetail') {
      router.push({
        path: '/procure/orderTrackDateil',
      })
      return
    }

    // 新建
    if (value == 'create') {
      router.push({
        path: '/procure/create',
        query: {
          order_no: '',
          from_type: value,
        },
      })
      return
    }

    if (!currentRow.value.length) {
      proxy.$Message('请选择需要操作的订单！', 'warning')
      return
    }

    if (currentRow.value.length > 1) {
      proxy.$Message('仅可以操作一条订单！', 'warning')
      return
    }

    const {
      order_no,
      status,
      status_str,
      order_status,
      is_allow_receipt,
      is_allow_pay,
      is_recharge,
    } = currentRow.value[0]

    // 确认收货
    if (value == 'confirm') {
      if (!is_allow_receipt) {
        proxy.$Message('该订单不可被操作！', 'warning')
        return
      }
      confirmReceiptDialogRef.value.open({ order_status, order_no })
      return
    }

    // 去付款
    if (value == 'toRecharge') {
      if (!is_recharge && !is_allow_pay) {
        proxy.$Message('此订单未到付款流程，无法付款！', 'warning')
        return
      }
      if (is_recharge && !is_allow_pay) {
        proxy.$Message('该订单已发起付款审核流程，请耐心等待！', 'warning')
        return
      }

      rechargeDialogRef.value.open(order_no)
      return
    }

    // 取消
    if (value == 'close') {
      if (status != 0 && status != 1) {
        proxy.$Message('该订单状态不可执行订单取消操作。', 'warning')
        return
      }

      ElMessageBox.confirm('该订单是否确定取消', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      })
        .then(() => {
          customerOrderUpdateStatus({ order_no, status: '2' }).then((res) => {
            proxy.$Message('取消成功', 'success')
            currentRow.value = []
            _GetProductList()
          })
        })
        .catch(() => {})
      return
    }
    // 复制
    if (value == 'copy') {
      router.push({
        path: '/procure/create',
        query: {
          order_no,
          from_type: value,
        },
      })
      return
    }
  }
  // 下载
  const _onExportBasicExcel = async () => {
    if (!data.dataSource.length) {
      proxy.$Message('导出数据为空，请进行筛选查询后再进行导出！', 'warning')
      return
    }

    const cloums = await orderTrackCloums.map((item: any) => {
      return {
        title: item.label,
        dataIndex: item.prop,
        width: item.width,
      }
    })
    data.pageSize = data.count

    await _GetProductList(false)

    const fileName = '订单明细'

    const list = data.dataSource.map((item: any) => {
      return {
        ...item,
        after_sale: '未出库',
        product_num: NumberFormat(item.product_num),
        ordered_num: NumberFormat(item.ordered_num),
        selling_price: MoneyFormat(item.selling_price, 2),
      }
    })
    await onExportBasicExcel(cloums, list, fileName, fileName)
    proxy.$Message('下载成功！', 'success')
    data.pageSize = 20
  }

  // 筛选项格式化
  const selectOptions = (value: string) => {
    if (!screenOptions && !value) return
    return OtherOutSearchSelect(value, screenOptions)
  }
  // 字段级格式化
  const _FieldFormat = (value: string, type = '') => {
    if (type == 'time') return DateFormat(value, 'YYYY-MM-DD')
    return FieldFormat(value, type)
  }

  // 生效状态tag_color
  const statusColor = (value: string) => {
    if (value == '草稿' || value == '信用额度充值') return 'warning'
    if (
      value == '已提交' ||
      value == '已确认' ||
      value == '卖方已接收' ||
      value == '已付款' ||
      value == '已出库' ||
      value == '已发货' ||
      value == '已发出' ||
      value == '已完成' ||
      value == '卖方已下单'
    )
      return 'success'
    if (value == '已取消') return 'danger'

    return 'info'
  }
  // 是否显示查看详情按钮
  const isShowDateil = (status: string | number) => {
    const _status = Number(status)
    if (_status == 0 || _status == 120) return false
    return true
  }

  // 筛选项
  const _GetScreenOptions = async () => {
    const cateRes = await getCustomerCategoryList() //买方
    const invoiceRes = await getBaseList('invoice_type') //发票类型
    screenOptions.categoryList = cateRes.data
    screenOptions.invoice_type = invoiceRes.data

    const searchBase = await getSearchBase()
    screenOptions.creator = searchBase.data.creator
    screenOptions.invoice_str = searchBase.data.invoice_str
    screenOptions.settle_organization = searchBase.data.settle_organization
  }
  // 获取数据
  const _GetProductList = async (lay = true) => {
    if (lay) data.loading = true

    let _searchForm: any = { ...searchForm }
    // 解构区间
    let vStart = ''
    let vEnd = ''
    if (vabRangeFormRef.value) {
      vStart = vabRangeFormRef.value.vStart
      vEnd = vabRangeFormRef.value.vEnd
    }

    if (!isCheck.value) {
      _searchForm = {}
      vStart = ''
      vEnd = ''
    }

    const create_time = _searchForm?.create_time

    let query = {
      order_status: _searchForm?.orderTrack_status
        ? StrShift(_searchForm.orderTrack_status)
        : '',
      product_code: _searchForm?.product_code
        ? StrShift(_searchForm.product_code)
        : '',
      start_time: create_time ? DateFormat(create_time[0]) : '',
      end_time: create_time ? DateFormat(create_time[1]) : '',
      order_no: _searchForm?.order_no || '',
      buyer_customer_id: _searchForm?.buyer_customer_id
        ? StrShift(_searchForm.buyer_customer_id)
        : '',
      create_user_id: _searchForm?.create_user_id
        ? StrShift(_searchForm.create_user_id)
        : '',
      order_price_start: vStart ? `${vStart}` : '',
      order_price_end: vEnd ? `${vEnd}` : '',
      invoice_str: _searchForm.invoice_str
        ? StrShift(_searchForm.invoice_str)
        : '',
      after_sale: _searchForm.after_sale
        ? StrShift(_searchForm.after_sale)
        : '',
      sales_org_name: _searchForm.sales_org_name
        ? StrShift(_searchForm.sales_org_name)
        : '',

      sort_field: sortInfo.sort_field || '',
      sort: sortInfo.sort || '',

      page: data.pageNum,
      pagesize: data.pageSize,
    }

    try {
      let res = await customerOrderList({ ...query })
      data.dataSource = res.data.list
      data.count = res.data.count
      data.loading = false
    } catch (error) {}
  }
  onMounted(() => {
    _GetProductList()
    _GetScreenOptions()
  })
</script>

<style lang="scss" scoped>
  @import '../../../components/public.scss';
  .tagStatus {
    :deep() {
      .el-tag {
        width: 82px !important;
      }
    }
  }
</style>
